package com.ciwong.epaper.modules.scan.ui;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.util.HomeWorkUtil;
import com.ciwong.epaper.modules.scan.adapter.QrInfoAdapter;
import com.ciwong.epaper.modules.scan.util.ScanJumpManager;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.DownloadProgressBar;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 电子报二维码信息扫描结果页面
 *
 * @author bin
 * @version ciwong v.1.0 2016/3/30 10:31
 * @since ciwong v.1.0
 */
public class EpaperQRInfoActivity extends BaseActivity {
    private ListView mLoadingLv;

    private QrInfoAdapter qrInfoAdapter;

    private List<DownLoadInfo> mList;
    private LinearLayout no_data;
    private Boolean isNoData;
    private List<EpaperInfo.Server> serverList;

    /**
     * 扫描后传过来的key
     */
    private String mKey;

    @Override
    protected int setView() {
        return R.layout.activity_loading_files;
    }

    @Override
    protected void findViews() {
        mLoadingLv = (ListView) findViewById(R.id.loading_files_lv);
        no_data = (LinearLayout) findViewById(R.id.ll_no_data);
    }

    @Override
    protected void initEvent() {
        mLoadingLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                DownLoadInfo downLoadInfo = (DownLoadInfo) parent.getItemAtPosition(position);
                mCurrentClickDownloadInfo = downLoadInfo;
                doClickListener(downLoadInfo, true);
            }
        });
        setDownloadProgressOnDismissListener(new DownloadProgressBar.OnDownLoadDialogDismissListener() {
            @Override
            public void ondDismiss(DownloadProgressBar downloadProgressBar) {
                int status = mCurrentDownloadInfo.getStatus();
                if (status == DownloadStatus.STATUS_LOADING || status == DownloadStatus.STATUS_DOWNLOADING) {
                    DownLoad.getInstance().pauseTask(mCurrentDownloadInfo);
                }
            }
        });


    }

    private void doClickListener(DownLoadInfo downloadInfo, boolean isHandClick) {
        DownLoadInfo downLoadInfo = downloadInfo;
        //              DownLoadInfo  downLoadInfo  =  DownLoad.getInstance().isPackageExist(info.getBookId(),info.getChapterId());
        if (downLoadInfo != null) {
            switch (downLoadInfo.getStatus()) {
                case DownloadStatus.STATUS_NORMAL:
                case DownloadStatus.STATUS_FAILED:
                case DownloadStatus.STATUS_FAILED_SDISFULL:
                case DownloadStatus.STATUS_FAILED_UNZIP:
                    if (DialogUtil.sdIsFullForDownload(EpaperQRInfoActivity.this, downLoadInfo)) {
                        DialogUtil.showSdFullDialog(
                                EpaperQRInfoActivity.this,
                                downLoadInfo.getSize());
                        return;
                    }
                    if (!NetworkUtils.isOnline()) {
                        ToastUtil.INSTANCE.toastCenterNoNetError();
                        return;
                    }
                    judgeDownloadmethod(downLoadInfo);
                    break;
                case DownloadStatus.STATUS_LOADING:
                    DownLoad.getInstance().pauseTask(downLoadInfo);
                    break;
                case DownloadStatus.STATUS_DOWNLOADING:
                    DownLoad.getInstance().pauseTask(downLoadInfo);
                    break;
                case DownloadStatus.STATUS_PAUSE:
                    if (!NetworkUtils.isOnline()) {
                        ToastUtil.INSTANCE.toastCenterNoNetError();
                        return;
                    }
                    if (NetworkUtils.isWifiOnline()) {
                        showDownloadDialog(downLoadInfo);
                        DownLoad.getInstance().resumeTask(downLoadInfo);
                    } else {
                        DialogUtil.showWIFIDialog(
                                EpaperQRInfoActivity.this, downLoadInfo);
                    }
                    break;
                case DownloadStatus.STATUS_COMPLETED:

                    if (!isHandClick) {
                        boolean downloadInfoTheSame = HomeWorkUtil.isDownloadInfoTheSameToClickDownLoadInfo(downLoadInfo, mCurrentClickDownloadInfo);
                        //解决打开两个不同类型作业问题
                        if (!downloadInfoTheSame) {
                            return;
                        }

                        //下载完成自动打开判断是否下载框还存在，如果不存在，不往下走
                        if (!isDownloadProessBarShowing()) {
                            return;
                        } else {
                            hideDownloadProgress();
                        }
                    }


                    if (isPreView) {
                        ScanJumpManager.jumpNewspaperQRDetailPreView(
                                R.string.go_back,
                                EpaperQRInfoActivity.this, downLoadInfo, mKey, serverList, isPreView);
                    } else {
                        ScanJumpManager.jumpNewspaperQRDetail(R.string.go_back, EpaperQRInfoActivity.this, downLoadInfo, mKey, serverList);
                    }
                    break;
            }
//                    }
        } else {//没有下载过
            if (DialogUtil.sdIsFullForDownload(EpaperQRInfoActivity.this, downLoadInfo)) {
                DialogUtil.showSdFullDialog(
                        EpaperQRInfoActivity.this,
                        downLoadInfo.getSize());
                return;
            }
            judgeDownloadmethod(downLoadInfo);
        }
    }

    private void judgeDownloadmethod(DownLoadInfo downLoadInfo) {
        if (NetworkUtils.isWifiOnline()) {
            showDownloadDialog(downLoadInfo);
            DownLoad.getInstance().addTask(downLoadInfo);
        } else {
            DialogUtil.showWIFIDialog(
                    EpaperQRInfoActivity.this, downLoadInfo);
        }
    }

    @Override
    protected void init() {
        setTitleText(R.string.qr_info);
        EventBus.getDownLoadInstance().register(this);
    }

    /**
     * 加载数据
     */
    @Override
    protected void loadData() {
        try {
            serverList = (List<EpaperInfo.Server>) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);
            isNoData = getIntent().getBooleanExtra(IntentFlag.INTENT_FLAG_TYPE, false);
            isPreView = getIntent().getBooleanExtra(IntentFlag.INTENT_FLAG_PRE_VIEW, false);
            if (isNoData) {
                no_data.setVisibility(View.VISIBLE);
                mLoadingLv.setVisibility(View.INVISIBLE);
            } else {
                mList = new ArrayList<DownLoadInfo>();
                mList = (ArrayList<DownLoadInfo>) getIntent()
                        .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
                CWLog.d("Scan", "Size=" + mList.size());
                mKey = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_STR);


                alreadyDownload(mList);
            }
            if (isKaoshi()) {
                mLoadingLv.setVisibility(View.GONE);
                no_data.setVisibility(View.VISIBLE);
                ((TextView) findViewById(R.id.show_tip)).setHint("");
                ((ImageView) findViewById(R.id.no_data_iv)).setImageResource(R.mipmap.no_erweima);
            }
        } catch (Exception e) {
            e.getStackTrace();
            CWLog.d("Scan", e.toString());
        }


    }

    /**
     * 是否是资源预览
     */
    boolean isPreView;

    /**
     * 判断是否是考试用书
     *
     * @return
     */
    private boolean isKaoshi() {
        if (serverList == null || serverList.size() == 0) {
            return false;
        }
        for (int i = 0; i < serverList.size(); i++) {
            if (serverList.get(i).getRequired() == 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
        super.onResume();
    }

    @Override
    protected void onStop() {

        if (EventBus.getDownLoadInstance().isRegistered(this) && !isTopActivity()) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
        }
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        DownLoadInfo info = item.getInfo();
        mCurrentDownloadInfo = info;
        if (mList.contains(info)) {
//            DownLoadInfo mCurrentInfo = mList.get(mList.indexOf(info));
//            mCurrentInfo.setStatus(info.getStatus());
//            mCurrentInfo.setProgress(info.getProgress());
//            qrInfoAdapter.notifyDataSetChanged();
            dealCircleProgress(info);
        }
    }

    private void alreadyDownload(List<DownLoadInfo> downLoadInfos) {
        try {
            if ((downLoadInfos != null && downLoadInfos.get(0).getIsPublish() == 1) || EApplication.BRAND_ID == EApplication.getInstance().getUserInfoBase().getUserId() || isPreView) {
                qrInfoAdapter = new QrInfoAdapter(EpaperQRInfoActivity.this, mList);
                mLoadingLv.setAdapter(qrInfoAdapter);
            } else {
                //资源没有发布
                no_data.setVisibility(View.VISIBLE);
                ((TextView) findViewById(R.id.show_tip)).setHint("");
                ((ImageView) findViewById(R.id.no_data_iv)).setImageResource(R.mipmap.saoyisao);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    private void dealCircleProgress(final DownLoadInfo info
    ) {
        switch (info.getStatus()) {
            case DownloadStatus.STATUS_FILE_DOWNLOAD:
                hideDownloadHorizontalProgressBar();
                hideCancelButtonOfDownloadProgress();
                break;
            case DownloadStatus.STATUS_COMPLETED:
                String packageDir = ESystem.getPackagesCatalogue(
                        info.getBookId(), info.getChapterId());
                if (new File(packageDir).exists()) {
                    doClickListener(info, false);
                } else {
                    hideDownloadProgress();
                    ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_SCAN_MODE, "解压后没有找到指定module", info.getResourceName() + ": " + info.getBookId() + " :" + info.getChapterId());
                }

                break;
            case DownloadStatus.STATUS_FAILED:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_SDISFULL:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_sdfull_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_UNZIP:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_unzip_and_retry);
                break;

            case DownloadStatus.STATUS_DOWNLOADING:
                if (HomeWorkUtil.isDownloadInfoTheSameToClickDownLoadInfo(info, mCurrentClickDownloadInfo)) {
                    updateDownloadProgress(info.getProgress());
                }

                break;
        }
    }


    private DownLoadInfo mCurrentDownloadInfo;
    private DownLoadInfo mCurrentClickDownloadInfo;

    public void showDownloadDialog(DownLoadInfo downLoadInfo) {
        showDownloadProgress();
        showCancelButtonOfDownloadProgress();
    }

}
